package com.activeMq.consumer.service;

import org.springframework.jms.annotation.JmsListenerConfigurer;
import org.springframework.jms.config.JmsListenerEndpointRegistrar;
import org.springframework.jms.config.SimpleJmsListenerEndpoint;
import org.springframework.stereotype.Service;

import javax.jms.JMSException;
import javax.jms.TextMessage;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class ActviceMqListenerService implements JmsListenerConfigurer {

    private AtomicInteger successCount = new AtomicInteger();
    private AtomicInteger failCount = new AtomicInteger();

    @Override
    public void configureJmsListeners(JmsListenerEndpointRegistrar registrar) {
        //接收消息
        SimpleJmsListenerEndpoint newEndpoint = new SimpleJmsListenerEndpoint();
        newEndpoint.setId("ActviceMqQuere");
        newEndpoint.setDestination("ActviceMqQuere");
        newEndpoint.setMessageListener(message -> this.handleMessage((TextMessage) message));

        //注册
        registrar.registerEndpoint(newEndpoint);
    }

    private void handleMessage(TextMessage message) {
        try {
            System.out.println(message.getText());
            successCount.addAndGet(1);
        } catch (JMSException e) {
            e.printStackTrace();
            failCount.addAndGet(1);
        }
    }

    public Map<String, Object> getReceivingQuantity() {
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("ServiceSuccessCount", successCount);
        dataMap.put("ServiceFailCount", failCount);
        return dataMap;
    }
}
